package com.meowcook.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.meowcook.common.AppResult;
import com.meowcook.dao.MembersMapper;
import com.meowcook.exception.AppException;
import com.meowcook.pojo.po.Members;
import com.meowcook.utils.COSClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-04-27
 * Time: 19:39
 */
@Slf4j
@Api(tags = "测试接口")
@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    private MembersMapper membersMapper;
    @Resource
    private ObjectMapper objectMapper;

    @ApiOperation("测试mvc")
    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }

    @ApiOperation("测试自定义异常捕获")
    @GetMapping("/error1")
    public String error1() {
        throw new AppException("test error1");
    }

    @ApiOperation("测试全局异常捕获")
    @GetMapping("/error2")
    public String error2() throws Exception {
        throw new Exception("test error2");
    }

    @ApiOperation("测试文件上传")
    @PostMapping("/fileUpload")
    public AppResult fileUpload(MultipartFile file) {
        if (file == null) {
            return AppResult.fail("上传文件为空");
        }
        try {
            String cookingImageUrl = COSClientUtils.uploadFile(file, "cooking_image");
            log.info("文件上传成功，访问路径为：{}", cookingImageUrl);
            return AppResult.success("上传成功", cookingImageUrl);
        }catch (InterruptedException e) {
            throw new RuntimeException();
        }
    }
    @ApiOperation("测试文件删除")
    @PostMapping("/fileDelete")
    public AppResult fileDelete(String path) {
        COSClientUtils.deleteFile(path);
        return AppResult.success("删除成功");
    }

    @ApiOperation("测试发送json数组")
    @GetMapping("/jsonArray")
    public AppResult<ArrayList<Long>> jsonArray() {
        Members members = membersMapper.selectByPrimaryKey(15L);
        String jsonArray = members.getInfoRecord();
        try {
            ArrayList<Long> list = objectMapper.readValue(jsonArray,
                    objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Long.class));
            return AppResult.success(list);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }
}
